//一级类目数组
var classonedata={}
var classonearr=[]
//二级类目数组
var classonedata2={}
var classonearr2=[]


//网站
querybrandWebsites()
function querybrandWebsites() {
    $.ajax({
        type: "POST",
        url: root.brandWebsite.query,
        cache: false,  //禁用缓存
        dataType: "json",
        async:false,//优先运行
        contentType: "application/json",
        data: JSON.stringify({

        }),
        success: function (data) {
            for (var i=0;i<data.data.data.length;i++){
                $("#websiteId").append("<option value=" + data.data.data[i].id + " >" + data.data.data[i].websiteName + "</option>")
            }

        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    });
}
Classaa()
function Classaa() {

    classonearr=[]
    $("#classA").html("")
    $("#classB").html("")
    var levelOne= ""
    var hierarchy=$('#classA li').length//序号
    $.ajax({
        type: "POST",
        url: root.brandWebsite.searchCategory,
        cache: false,  //禁用缓存
        dataType: "json",
        contentType: "application/json",
        data: JSON.stringify({
            "websiteId":$("#websiteId").val(),
            "categoryId":"",
        }),
        success: function (data) {
            var levelOnedata=data.data.categoryList
            for (var i=0;i<levelOnedata.length;i++){
                hierarchy++;
                classonedata={
                    "id":levelOnedata[i].id,
                    "sort":hierarchy,
                    "level":1,
                    "categoryName":levelOnedata[i].categoryName,
                    "isDelete":0,
                    "createUser":JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name
                }
                classonearr.push(classonedata)
            }
            console.log(classonearr)
            for (var j=0;j<classonearr.length;j++){
                levelOne += '<li class="clearfix pl-10 mb-5">' +
                    '                            <div class="f-l pd-5">' +
                    '                                <span  class="freight_1">'+classonearr[j].sort+'</span>' +
                    '                                    <input class="class_nametext" id="classification'+classonearr[j].sort+'" style="display: none" type="text" value="" maxlength="10" autocomplete="off" onkeyup="value=value.replace(/[^\\a-zA-Z\u4E00-\u9FA5]/g,\'\')" onbeforepaste="clipboardData.setData(\'text\',clipboardData.getData(\'text\').replace(/[^\\a-zA-Z\u4E00-\u9FA5]/g,\'\'))">' +
                    '                                    <span class="clss_name_text" data-id="'+classonearr[j].sort+'" data-oneid="'+classonearr[j].id+'"  id="classificationName'+classonearr[j].sort+'"  onclick="Twodata(this,'+classonearr[j].sort+')">'+classonearr[j].categoryName+'</span>' +
                    '                                    <div class="class_opter">' +
                    '                                    <span class="calss_opter_modify colorblue" id="buttonone'+classonearr[j].sort+'" onclick="modifyName('+classonearr[j].sort+')">修改</span>' +
                    '                                    <span class="calss_opter_modify colorblue" style="display: none" id="buttononeadd'+classonearr[j].sort+'" onclick="modifyNameadd('+classonearr[j].sort+','+classonearr[j].id+')">保存</span>' +
                    '                                    <span class="calss_opter_delt colorblue" onclick="deletedata('+classonearr[j].id+','+classonearr[j].sort+')">删除</span>' +
                    '                                    </div>' +
                    '                                    <div class="class_sortbox">' +
                    '                                    <img style="width: 12px;height: 18px;margin-left: 25px;" onclick="onclick_updown(\'up\', '+classonearr[j].sort+')" src="../../../img/gw_up.png">' +
                    '                                    <img style="width: 12px;height: 18px;margin-left: 12px;"  onclick="onclick_updown(\'down\', '+classonearr[j].sort+')" src="../../../img/gw_down.png">' +
                    '                                    </div>' +
                    '                                    </div>' +
                    '                    </li>'
            }


            $("#classA").html(levelOne)

                //填充数组

            console.log(classonearr)
        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    });
}


//添加类目
var dataidArr=[]
function addCategorys(type) {
    if(type==1){
        //一级类目保存按钮展示
        $("#classAadd").css({
            display: "block"
        })
    }else {
        //二级类目保存按钮展示
        var classdatas= $("#classA").find(".clss_name_text");
       if(classdatas.length!=0){
           for (var i=0;i<classdatas.length;i++){
               if($(classdatas[i]).hasClass("backColor")){
                   dataidArr.push($(classdatas[i]).attr('data-id'))

               }
           }
           if(dataidArr!=""){
               $("#classBadd").css({
                   display: "block"
               })
           }else {
               layer.msg('请选择一级类目设置', {icon: 5, time: 1000});
               $("#classBadd").css({
                   display: "none"
               })
           }


       }else {
           layer.msg('请选择一级类目设置', {icon: 5, time: 1000});
           $("#classBadd").css({
               display: "none"
           })
       }

    }

}
//添加一级类目
function addOne() {
    var hierarchy=$('#classA li').length+1//序号
    var dataOnes=$("#dataOne").val()//添加名称
    if(dataOnes==""){
        layer.msg('请填写必填信息', {icon: 5, time: 1000});
        return false
    }
    for (var p=0;p<classonearr.length;p++) {
        if ($("#dataOne").val()==classonearr[p].categoryName) {
            layer.msg('名称重复，请重新填写', {icon: 5, time: 1000});
            return false
        }
    }
    if($('#classA li').length>=30){
        layer.msg('一级类目最多可设置30个', {icon: 5, time: 1000});
        return false;
   }

    $.ajax({
        type: "POST",
        url: root.brandWebsite.productsave,
        cache: false,  //禁用缓存
        dataType: "json",
        contentType: "application/json",
        data: JSON.stringify({
            "websiteId":$("#websiteId").val(),
            "categoryName":dataOnes,
            "parentCategoryId":0,
            "level":1,
            "sort":hierarchy,
            "createUser":JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name
        }),
        success: function (data) {
            if(data.errorCode==0){
                $.Huimodalalert('保存成功',2000);
                Classaa()
                $("#dataOne").val("")
            }else {
                $.Huimodalalert(data.msg,2000);
            }

        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    });

}
//修改一级类目名称
function modifyName(val) {
    for (var i=0;i<classonearr.length;i++){
        if(classonearr[i].sort==val){
            $("#classification"+val).val(classonearr[i].categoryName)
        }
    }

    $("#classificationName"+val).css({
        display:"none"
    })
    $("#classification"+val).css({
        display:"inline"
    })
    $("#buttonone"+val).css({
        display:"none"
    })
    $("#buttononeadd"+val).css({
        display:"inline"
    })

}
//一级类目保存
function modifyNameadd(sort,val) {
    if($("#classification"+sort).val()==""){
        layer.msg('请填写名称', {icon: 5, time: 1000});
        return false;
    }
    for (var p=0;p<classonearr.length;p++) {
        if(val!=classonearr[p].id){
            if ($("#classification"+sort).val()==classonearr[p].categoryName) {
                layer.msg('名称重复，请重新填写', {icon: 5, time: 1000});
                return false
            }
        }

    }
   if($("#classification"+sort).val().length > Number(10)){
       layer.msg('最大长度10位，请重新填写', {icon: 5, time: 1000});
       $("#classification"+sort).val("")
       return false;
   }


    var productupdate={}
    var productupdatearr=[]
    productupdate={
        "level":1,
        "id":val,
        "sort":sort,
        "categoryName":$("#classification"+sort).val(),
        "isDelete":0,
        "createUser":JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name
    }
    productupdatearr.push(productupdate)
    $.ajax({
        type: "POST",
        url: root.brandWebsite.productupdate,
        cache: false,  //禁用缓存
        dataType: "json",
        contentType: "application/json",
        data: JSON.stringify({
            "brandWebsiteProductCategorys":productupdatearr
        }),
        success: function (data) {
            if(data.errorCode==0){
                $.Huimodalalert('修改成功',2000);
                Classaa()
            }else if(data.errorCode==5){
                $.Huimodalalert(data.sub_msg,2000);
            }else {
                $.Huimodalalert(data.msg,2000);
            }

        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    });

   //按钮显示控制
    $("#classificationName"+sort).css({
        display:"inline-block"
    })
    $("#classification"+sort).css({
        display:"none"
    })
    $("#buttonone"+sort).css({
        display:"inline"
    })
    $("#buttononeadd"+sort).css({
        display:"none"
    })

}
//一级类目删除

function deletedata(val,sort) {
    var productupdate={}
    var productupdatearr=[]
    productupdate={
        "id":val,
        "level":1,
        "sort":sort,
        "categoryName":"",
        "isDelete":1,
        "createUser":JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name
    }
    productupdatearr.push(productupdate)
    $.ajax({
        type: "POST",
        url: root.brandWebsite.productupdate,
        cache: false,  //禁用缓存
        dataType: "json",
        contentType: "application/json",
        data: JSON.stringify({
            "brandWebsiteProductCategorys":productupdatearr
        }),
        success: function (data) {
            if(data.errorCode==0){
                $.Huimodalalert('删除成功',2000);
                Classaa()
            }else if(data.errorCode==5){
                $.Huimodalalert(data.sub_msg,2000);
            }else {
                $.Huimodalalert(data.msg,2000);
            }

        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    });
}
//一级类目上移下移
function onclick_updown(updown, order,){
    $("#classB").html("")
    dataidArr=[]
    $("#classA").find(".clss_name_text").removeClass("backColor")
    var o_order, n_order;
    o_order = order;
    o_innerHTML = document.getElementById("classificationName" + o_order).innerHTML;
    if (updown == "down"){

        n_order = order + 1;
        downData(classonearr,order-1)

    } else{

        n_order = order - 1;
        upData(classonearr,n_order)

    }
   /* n_innerHTML = document.getElementById("classificationName" + n_order).innerHTML;
    document.getElementById("classificationName" + o_order).innerHTML = n_innerHTML;
    document.getElementById("classificationName" + n_order).innerHTML = o_innerHTML;*/

}

var swapItems = function(arr, index1, index2){
    arr[index1] = arr.splice(index2,1,arr[index1])[0]
    return arr
}
/*上移*/
function upData (arr, index) {
    if (arr.length > 1 && index !== 0) {
        classonearr = swapItems(arr, index, index - 1)
    }
    //改变数组元素oneid
    for (var i=0; i<classonearr.length; i++) {
        var classdatas= $("#classA").find(".clss_name_text");
        for (var i=0;i<classdatas.length;i++){
            console.log($(classdatas[i]).attr('data-id'))
            console.log(classonearr[i].sort)
                classonearr[i].sort= $(classdatas[i]).attr('data-id')
        }
    }
    datasAll()
    console.log(classonearr)

}
/*下移*/
function  downData (arr, index) {
    if (arr.length > 1 && index !== (arr.length - 1)) {
        classonearr = swapItems(arr, index, index + 1)
    }
    //改变数组元素oneid
    for (var i=0; i<classonearr.length; i++) {
        var classdatas= $("#classA").find(".clss_name_text");
        for (var i=0;i<classdatas.length;i++){
            classonearr[i].sort= $(classdatas[i]).attr('data-id')
        }
    }
    datasAll()
}
//每次上下移后都清空数据重新渲染
function datasAll() {
    $("#classA").html("")
    var leveldatad=""
    for (var j=0;j<classonearr.length;j++){
        leveldatad += '<li class="clearfix pl-10 mb-5">' +
            '                            <div class="f-l pd-5">' +
            '                                <span  class="freight_1">'+classonearr[j].sort+'</span>' +
            '                                    <input class="class_nametext" id="classification'+classonearr[j].sort+'" style="display: none" type="text" value="" maxlength="10" autocomplete="off" onkeyup="value=value.replace(/[^\\a-zA-Z\u4E00-\u9FA5]/g,\'\')" onbeforepaste="clipboardData.setData(\'text\',clipboardData.getData(\'text\').replace(/[^\\a-zA-Z\u4E00-\u9FA5]/g,\'\'))">' +
            '                                    <span class="clss_name_text" data-id="'+classonearr[j].sort+'" data-oneid="'+classonearr[j].id+'"  id="classificationName'+classonearr[j].sort+'"  onclick="Twodata(this,'+classonearr[j].sort+')">'+classonearr[j].categoryName+'</span>' +
            '                                    <div class="class_opter">' +
            '                                    <span class="calss_opter_modify colorblue" id="buttonone'+classonearr[j].sort+'" onclick="modifyName('+classonearr[j].sort+')">修改</span>' +
            '                                    <span class="calss_opter_modify colorblue" style="display: none" id="buttononeadd'+classonearr[j].sort+'" onclick="modifyNameadd('+classonearr[j].sort+','+classonearr[j].id+')">保存</span>' +
            '                                    <span class="calss_opter_delt colorblue" onclick="deletedata('+classonearr[j].id+','+classonearr[j].sort+')">删除</span>' +
            '                                    </div>' +
            '                                    <div class="class_sortbox">' +
            '                                    <img style="width: 12px;height: 18px;margin-left: 25px;" onclick="onclick_updown(\'up\', '+classonearr[j].sort+')" src="../../../img/gw_up.png">' +
            '                                    <img style="width: 12px;height: 18px;margin-left: 12px;"  onclick="onclick_updown(\'down\', '+classonearr[j].sort+')" src="../../../img/gw_down.png">' +
            '                                    </div>' +
            '                                    </div>' +
            '                    </li>'
    }


    $("#classA").html(leveldatad)
}
//选中类目变底色
function Twodata(e,val) {
    $(e).addClass("backColor")
    $(e).parent().parent().siblings().find(".clss_name_text").removeClass("backColor");
    Classbb()
}
//二级类目展示
function Classbb() {
    $("#classB").html("")
    //获取一级分类id
    var categoryIds=""
    var hierarchy=$('#classB li').length;
    var classdatas= $("#classA").find(".clss_name_text");
    for (var i=0;i<classdatas.length;i++){
    if($(classdatas[i]).hasClass("backColor")){
        categoryIds=$(classdatas[i]).attr('data-oneid')
    }
    }
    $.ajax({
        type: "POST",
        url: root.brandWebsite.searchCategory,
        cache: false,  //禁用缓存
        dataType: "json",
        contentType: "application/json",
        data: JSON.stringify({
            "websiteId":$("#websiteId").val(),
            "categoryId":categoryIds,
        }),
        success: function (data) {
            var levelTwo=""
            var twodatas=data.data.sedCategoryList
            for (var i=0;i<twodatas.length;i++){
                hierarchy++;
                classonedata2={
                    sedCategoryid:twodatas[i].id,
                    id:hierarchy,
                    categoryName:twodatas[i].categoryName
                }
                classonearr2.push(classonedata2)

                levelTwo += '<li class="clearfix pl-10 mb-5">' +
                    '                            <div class="f-l pd-5">' +
                    '                                <span class="freight_2">'+hierarchy+'</span>' +
                    '                                    <input class="class_nametext" id="classificationTwo'+hierarchy+'" style="display: none" type="text" value="" maxlength="10" autocomplete="off" onkeyup="value=value.replace(/[^\\a-zA-Z\u4E00-\u9FA5]/g,\'\')" onbeforepaste="clipboardData.setData(\'text\',clipboardData.getData(\'text\').replace(/[^\\a-zA-Z\u4E00-\u9FA5]/g,\'\'))">' +
                    '                                    <span class="clss_name_text" id="classificationNameTwo'+hierarchy+'" >'+twodatas[i].categoryName+'</span>' +
                    '                                    <div class="class_opter">' +
                    '                                    <span class="calss_opter_modify colorblue" id="buttononeTwo'+hierarchy+'" onclick="modifyNameTwo('+hierarchy+')">修改</span>' +
                    '                                    <span class="calss_opter_modify colorblue" style="display: none" id="buttononeaddTwo'+hierarchy+'" onclick="modifyNameaddTwo('+hierarchy+','+twodatas[i].id+')">保存</span>' +
                    '                                    <span class="calss_opter_delt colorblue" onclick="deletedataTwo('+hierarchy+','+twodatas[i].id+')">删除</span>' +
                    '                                    </div>' +
                    '                                    </div>' +
                    '                    </li>'
            }

            $("#classB").html(levelTwo)
        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    });
}

//添加二级类目
function addTwo() {
    var categoryIds=""
    var classdatas= $("#classA").find(".clss_name_text");
    for (var i=0;i<classdatas.length;i++){
        if($(classdatas[i]).hasClass("backColor")){
            categoryIds=$(classdatas[i]).attr('data-oneid')
        }
    }
    var hierarchy=$('#classB li').length+1;
    var dataTwos=$("#dataTwo").val()
    if($("#dataTwo").val()==""){
        layer.msg('请填写名称', {icon: 5, time: 1000});
        return false;
    }
    for (var p=0;p<classonearr2.length;p++) {
        if ($("#dataTwo").val()==classonearr2[p].categoryName) {
            layer.msg('名称重复，请重新填写', {icon: 5, time: 1000});
            return false
        }
    }
    if($('#classB li').length>=30){
        layer.msg('二级类目最多可设置30个', {icon: 5, time: 1000});
        return false;
    }

    $.ajax({
        type: "POST",
        url: root.brandWebsite.productsave,
        cache: false,  //禁用缓存
        dataType: "json",
        contentType: "application/json",
        data: JSON.stringify({
            "websiteId":$("#websiteId").val(),
            "categoryName":dataTwos,
            "parentCategoryId":categoryIds,
            "level":2,
            "sort":hierarchy,
            "createUser":JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name
        }),
        success: function (data) {
            if(data.errorCode==0){
                $.Huimodalalert('保存成功',2000);
                Classbb()
                $("#dataTwo").val("")
            }else {
                $.Huimodalalert(data.msg,2000);
            }

        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    });


}

//修改二级类目名称
function modifyNameTwo(val) {
    for (var i=0;i<classonearr2.length;i++){
        if(classonearr2[i].id==val){
            $("#classificationTwo"+val).val(classonearr2[i].categoryName)
        }
    }
    $("#classificationNameTwo"+val).css({
        display:"none"
    })
    $("#classificationTwo"+val).css({
        display:"inline"
    })
    $("#buttononeTwo"+val).css({
        display:"none"
    })
    $("#buttononeaddTwo"+val).css({
        display:"inline"
    })

}
//保存二级类目
function modifyNameaddTwo(sort,val) {
    if($("#classificationTwo"+sort).val()==""){
        layer.msg('请填写名称', {icon: 5, time: 1000});
        return false;
    }
    for (var p=0;p<classonearr2.length;p++) {
        if(val!=classonearr2[p].sedCategoryid){
            if ($("#classificationTwo"+sort).val()==classonearr2[p].categoryName) {
                layer.msg('名称重复，请重新填写', {icon: 5, time: 1000});
                return false
            }
        }

    }
    if($("#classificationTwo"+sort).val().length > Number(10)){
        layer.msg('最大长度10位，请重新填写', {icon: 5, time: 1000});
        $("#classificationTwo"+sort).val("")
        return false;
    }

    var productupdate={}
    var productupdatearr=[]
    productupdate={
        "level":2,
        "id":val,
        "sort":sort,
        "categoryName":$("#classificationTwo"+sort).val(),
        "isDelete":0,
        "createUser":JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name
    }
    productupdatearr.push(productupdate)
    $.ajax({
        type: "POST",
        url: root.brandWebsite.productupdate,
        cache: false,  //禁用缓存
        dataType: "json",
        contentType: "application/json",
        data: JSON.stringify({
            "brandWebsiteProductCategorys":productupdatearr
        }),
        success: function (data) {
            if(data.errorCode==0){
                $.Huimodalalert('修改成功',2000);
                Classbb()
            }else if(data.errorCode==5){
                $.Huimodalalert(data.sub_msg,2000);
            }else {
                $.Huimodalalert(data.msg,2000);
            }

        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    });

    //按钮显示
    $("#classificationNameTwo"+sort).css({
        display:"inline-block"
    })
    $("#classificationTwo"+sort).css({
        display:"none"
    })
    $("#buttononeTwo"+sort).css({
        display:"inline"
    })
    $("#buttononeaddTwo"+sort).css({
        display:"none"
    })
}
//删除二级类目
function deletedataTwo(sort,val) {
    var productupdate={}
    var productupdatearr=[]
    productupdate={
        "id":val,
        "level":2,
        "sort":sort,
        "categoryName":"",
        "isDelete":1,
        "createUser":JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name
    }
    productupdatearr.push(productupdate)
    $.ajax({
        type: "POST",
        url: root.brandWebsite.productupdate,
        cache: false,  //禁用缓存
        dataType: "json",
        contentType: "application/json",
        data: JSON.stringify({
            "brandWebsiteProductCategorys":productupdatearr
        }),
        success: function (data) {
            if(data.errorCode==0){
                $.Huimodalalert('删除成功',2000);
                Classbb()
            }else if(data.errorCode==5){
                $.Huimodalalert(data.sub_msg,2000);
            }else {
                $.Huimodalalert(data.msg,2000);
            }

        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    });
}
//保存更新
function saveUpdates() {
    $.ajax({
        type: "POST",
        url: root.brandWebsite.productupdate,
        cache: false,  //禁用缓存
        dataType: "json",
        contentType: "application/json",
        data: JSON.stringify({
            "brandWebsiteProductCategorys":classonearr
        }),
        success: function (data) {
            if(data.errorCode==0){
                $.Huimodalalert('保存成功',2000);
                Classaa()
            }else if(data.errorCode==5){
                $.Huimodalalert(data.sub_msg,2000);
            }else {
                $.Huimodalalert(data.msg,2000);
            }

        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    });
}